package com.guigu.liuzhireng.controller;

import com.guigu.liuzhireng.pojo.Account;
import com.guigu.liuzhireng.service.AccountService;
import com.guigu.liuzhireng.service.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    AccountService accountService;
    @Autowired
    AuthorizationService authorizationService;

    @RequestMapping("Login.do")
    @ResponseBody
    public Integer Login(Account account, HttpSession session) {
        Account user = accountService.login(account);
        if (user != null) {
            session.setAttribute("user", user);

            List<String> strings = authorizationService.QueryAuth(user.getAccount());
            session.setAttribute("auths",strings);
            return 0;
        } else {
            return 1;
        }
    }

    @RequestMapping("Register.do")
    public String Register(Account account, MultipartFile filename, HttpServletRequest req, Model model) throws IOException {
        Account acc01 = accountService.loadAccount(account.getAccount());
        if (filename == null) {
            account.setImage(null);
        } else {
            File file = new File(req.getServletContext().getRealPath("/image"));
            if (!file.exists()) {
                file.mkdirs();
            }
            String newFileName = UUID.randomUUID().toString();
            String originalFilename = filename.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            filename.transferTo(new File(file.toString() + "/" + newFileName + substring));
            account.setImage(newFileName + substring);
        }
        accountService.insert(account);
        return "login.html";
    }

    @RequestMapping("ChangePWD.do")
    @ResponseBody
    public int ChangePWD(Account account) {
        Account acc01 = accountService.loadAccount(account.getAccount());
        if (acc01 != null) {
            return accountService.update(account);
        } else {
            return -1;
        }
    }

    @RequestMapping("TuiChu.do")
    public void Login(HttpSession session, HttpServletResponse resp) throws IOException {
        session.removeAttribute("user");
        resp.sendRedirect("login.html");
    }


}
